#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
using namespace std;

#define QUEUE_LISTEN 20

class Sock
{
public:
    Sock(int *sockptr = nullptr)
    {
        // 创建套接字
        _sock = socket(AF_INET, SOCK_STREAM, 0);
        if (_sock < 0)
        {
            cout << "sock fail:" << strerror(errno) << endl;
            exit(1);
        }
        int fl = fcntl(_sock, F_GETFL);
        if (fl < 0)
            cout << "fcntl fail: " << strerror(errno) << endl;
        fcntl(_sock, F_SETFL, fl | O_NONBLOCK);
        if (sockptr)
            *sockptr = _sock;
    }
    void Bind(uint16_t port, string ip = INADDR_ANY)
    {
        sockaddr_in sever;
        memset(&sever, sizeof sever, 0);
        sever.sin_addr.s_addr = (inet_addr(ip.c_str()) == INADDR_ANY ? INADDR_ANY : inet_addr(ip.c_str()));
        sever.sin_family = AF_INET;
        sever.sin_port = htons(port);
        int ret = bind(_sock, (sockaddr *)(&sever), sizeof sever);
        if (ret < 0)
        {
            cout << "bind fail:" << strerror(errno) << endl;
            exit(2);
        }
    }
    void Listen()
    {
        int ret = listen(_sock, QUEUE_LISTEN);
        if (ret < 0)
        {
            cout << "listen fail :" << strerror(errno) << endl;
            exit(3);
        }
    }
    static void Connect(int sock, sockaddr_in *sever)
    {
        int ret = connect(sock, (sockaddr *)sever, sizeof(*sever));
        if (ret < 0)
        {
            cout << "connect fail :" << strerror(errno) << endl;
            exit(4);
        }
    }
    int Accept()
    {
        sockaddr_in client;
        memset(&client, sizeof client, 0);
        socklen_t len = sizeof(client);
        int clientsock = accept(_sock, (sockaddr *)(&client), &len);
        if (clientsock < 0)
        {
            cout << "accept fail: " << strerror(errno) << endl;
            exit(5);
        }
        return clientsock;
    }
    ~Sock()
    {
        if (_sock > 0)
            close(_sock);
    }

private:
    int _sock;
};